import {activeTheme, ThemeOptions, themes} from '../config';
import {ILeetCodeUser, JuejinUserData} from '../types';
import {SvgSanitizerService} from './svg-sanitizer.service';

// 卡片类型定义
export enum CardType {
    LEETCODE = 'leetcode',
    GITHUB = 'github',
    CSDN = 'csdn',
    JUEJIN = 'juejin',
    BILIBILI = 'bilibili',
    ERROR = 'error'
}

/**
 * 生成LeetCode统计卡片
 * @param data LeetCode用户数据
 * @param theme 主题配置
 * @returns SVG字符串
 */
const generateLeetCodeCard = (data: ILeetCodeUser | null, theme: ThemeOptions = activeTheme): string => {
    if (!data) {
        return generateErrorCard('未找到LeetCode用户数据', theme);
    }

    const easySolved = data.easySolved || 0;
    const mediumSolved = data.mediumSolved || 0;
    const hardSolved = data.hardSolved || 0;
    const totalSolved = data.totalSolved || 0;

    // 获取region信息 (如果有)
    const region = data.region || 'US';
    const regionColor = region === 'CN' ? '#e74c3c' : '#3498db';

    // 当前日期
    const currentDate = new Date().toLocaleDateString();

    // 生成SVG - 增加高度为240，为底部文本留出更多空间
    // 使用sanitizeUserContent清理用户输入数据
    const safeUsername = SvgSanitizerService.sanitizeUserContent(data.username);
    const safeAcceptanceRate = SvgSanitizerService.sanitizeUserContent(data.acceptanceRate || 'N/A');
    
    return SvgSanitizerService.sanitize(`<svg xmlns="http://www.w3.org/2000/svg" width="495" height="240" viewBox="0 0 495 240">
    <style>
      .text { font-family: ${theme.fonts.family}; font-size: ${theme.fonts.size.normal}; fill: ${theme.colors.text.primary}; }
      .header { font-family: ${theme.fonts.family}; font-size: ${theme.fonts.size.title}; font-weight: bold; fill: ${theme.colors.text.title}; }
      .small { font-family: ${theme.fonts.family}; font-size: ${theme.fonts.size.small}; fill: ${theme.colors.text.secondary}; }
      .easy { fill: ${theme.colors.stats.easy}; }
      .medium { fill: ${theme.colors.stats.medium}; }
      .hard { fill: ${theme.colors.stats.hard}; }
      .total { fill: ${theme.colors.stats.total}; }
      .region-pill { font-family: ${theme.fonts.family}; font-size: 12px; font-weight: bold; fill: #ffffff; }
      .footer { font-family: ${theme.fonts.family}; font-size: 10px; fill: ${theme.colors.text.secondary}; }
    </style>
    <rect width="495" height="240" fill="${theme.colors.background}" rx="${theme.card.borderRadius}" ry="${theme.card.borderRadius}" stroke="${theme.colors.border}" stroke-width="1"/>
    <text x="30" y="40" class="header">LeetCode 解题统计</text>
    
    <!-- 区域标识 -->
    <rect x="442" y="25" width="30" height="20" rx="10" ry="10" fill="${regionColor}" />
    <text x="457" y="39" text-anchor="middle" class="region-pill">${region}</text>
    
    <!-- 调整用户名位置，避免与区域标识重叠 -->
    <text x="380" y="40" text-anchor="end" class="small">用户: ${safeUsername}</text>
    
    <rect x="30" y="60" width="435" height="1" fill="${theme.colors.border}"/>
    
    <text x="30" y="90" class="text">总计解题:</text>
    <text x="465" y="90" text-anchor="end" class="text total">${totalSolved}</text>
    
    <text x="30" y="120" class="text">简单:</text>
    <text x="465" y="120" text-anchor="end" class="text easy">${easySolved}</text>
    
    <text x="30" y="150" class="text">中等:</text>
    <text x="465" y="150" text-anchor="end" class="text medium">${mediumSolved}</text>
    
    <text x="30" y="180" class="text">困难:</text>
    <text x="465" y="180" text-anchor="end" class="text hard">${hardSolved}</text>
    
    <text x="250" y="90" text-anchor="middle" class="small">通过率: ${safeAcceptanceRate}</text>
    
    <!-- 分隔线 -->
    <rect x="25" y="200" width="445" height="1" fill="${theme.colors.border}"/>
    
    <text x="25" y="220" text-anchor="start" class="footer">Generated by GitHub Profile Statistics Card</text>
    <text x="470" y="220" text-anchor="end" class="footer" font-size="10">更新时间: ${currentDate}</text>
  </svg>`);
}

/**
 * 生成GitHub访问计数卡片
 * @param count 访问计数
 * @param avatarUrl 头像URL
 * @param username 用户名
 * @param theme 主题配置
 * @returns SVG字符串
 */
const generateGitHubCounterCard = (
    count: number,
    avatarUrl: string | null = null,
    username: string = '',
    theme: ThemeOptions = activeTheme
): string => {
    // 安全处理用户数据
    const safeUsername = SvgSanitizerService.sanitizeUserContent(username);
    
    // 安全处理计数显示
    let countDisplay = Number(count).toString();
    if (count >= 1000) {
        countDisplay = (count / 1000).toFixed(1) + 'k';
    }

    // 计算当前日期
    const currentDate = new Date().toLocaleDateString();

    // 优化的基本SVG - 现代化设计
    let svg = `<svg xmlns="http://www.w3.org/2000/svg" width="320" height="140" viewBox="0 0 320 140">
    <defs>
      <linearGradient id="bgGradient" x1="0%" y1="0%" x2="100%" y2="100%">
        <stop offset="0%" stop-color="${theme.colors.background}" />
        <stop offset="100%" stop-color="${theme.colors.background}DD" />
      </linearGradient>
      <filter id="dropShadow" x="-5%" y="-5%" width="110%" height="110%">
        <feDropShadow dx="0" dy="2" stdDeviation="2" flood-color="#00000033" />
      </filter>
      <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&amp;display=swap');
        .container { filter: url(#dropShadow); }
        .text { font-family: 'Inter', ${theme.fonts.family}; font-size: ${theme.fonts.size.normal}; fill: ${theme.colors.text.primary}; }
        .count { font-family: 'Inter', ${theme.fonts.family}; font-size: 42px; font-weight: 700; fill: ${theme.colors.stats.count}; }
        .small { font-family: 'Inter', ${theme.fonts.family}; font-size: ${theme.fonts.size.small}; fill: ${theme.colors.text.secondary}; }
        .title { font-family: 'Inter', ${theme.fonts.family}; font-size: ${theme.fonts.size.title}; font-weight: 600; fill: ${theme.colors.text.title}; }
        .project { font-family: 'Inter', ${theme.fonts.family}; font-size: 8px; fill: ${theme.colors.text.secondary}; }
        .footer { font-family: ${theme.fonts.family}; font-size: 8px; fill: ${theme.colors.text.secondary}; }
      </style>
    </defs>
    
    <g class="container">
      <!-- 背景和边框 -->
      <rect width="320" height="140" fill="url(#bgGradient)" rx="${theme.card.borderRadius}" ry="${theme.card.borderRadius}" stroke="${theme.colors.border}" stroke-width="1"/>
    `;

    // 添加用户头像或默认GitHub图标
    if (avatarUrl) {
        // 检查是否是 base64 格式的头像
        const isBase64 = avatarUrl.startsWith('data:image');
        const imageUrl = isBase64 ? avatarUrl : `${avatarUrl}`;

        svg += `
      <!-- 用户头像 -->
      <g transform="translate(20, 30)">
        <!-- 圆形头像背景 -->
        <circle cx="18" cy="18" r="18" fill="#FFFFFF" />
        <!-- 用户头像 - 剪裁为圆形 -->
        <clipPath id="userAvatarClip">
          <circle cx="18" cy="18" r="18" />
        </clipPath>
        <image x="0" y="0" width="36" height="36" href="${imageUrl}" clip-path="url(#userAvatarClip)" />
      </g>
        
        <!-- 用户名和标题 -->
        <text x="70" y="45" class="title">GitHub 访问</text>
        <text x="70" y="65" class="small">@${safeUsername}</text>

      <!-- 分隔线 -->
      <rect x="25" y="110" width="285" height="1" fill="${theme.colors.border}"/>

      <text x="15" y="130" text-anchor="start" class="footer">Generated by GitHub Profile Statistics Card</text>
      <text x="285" y="130" text-anchor="end" class="footer">更新时间: ${currentDate}</text>
    `;
    } else {
        svg += `
      <!-- GitHub 图标 -->
      <svg x="20" y="28" width="36" height="36" viewBox="0 0 24 24" class="github-icon">
        <path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z"/>
      </svg>
      
      <!-- 标题 -->
      <text x="70" y="45" class="title">GitHub 访问</text>
    `;
    }

    // 添加计数和更新日期
    svg += `
      <!-- 计数 -->
      <text x="160" y="95" text-anchor="middle" class="count">${countDisplay}</text>
      
      <!-- 分隔线 -->
      <line x1="40" y1="110" x2="280" y2="110" stroke="${theme.colors.border}" stroke-width="0.5" opacity="0.5"/>
      
    </g>
  </svg>`;

    return SvgSanitizerService.sanitize(svg);
}

/**
 * 生成CSDN统计卡片
 * @param data CSDN用户数据
 * @param theme 主题配置
 * @returns SVG字符串
 */
const generateCSDNCard = (data: any, theme: ThemeOptions = activeTheme): string => {
    if (!data) {
        return generateErrorCard('无法获取CSDN数据', theme);
    }

    const {
        articleCount,
        followers,
        likes,
        views,
        comments,
        points,
        username,
        // 新增字段
        rank,
        codeAge,
        level,
        monthPoints
    } = data;

    // 数据格式化，大于1000的数字以k为单位
    const formatNumber = (num: number): string => {
        if (num >= 1000000) {
            return (num / 1000000).toFixed(1) + 'M';
        } else if (num >= 1000) {
            return (num / 1000).toFixed(1) + 'K';
        }
        return num.toString();
    };

    // 当前日期
    const currentDate = new Date().toLocaleDateString();

    // 卡片高度增加以容纳更多数据
    // 安全处理用户数据
    const safeUsername = SvgSanitizerService.sanitizeUserContent(username || '');
    const safeRank = SvgSanitizerService.sanitizeUserContent(rank ? formatNumber(rank) : 'N/A');
    const safeCodeAge = SvgSanitizerService.sanitizeUserContent(codeAge || 'N/A');
    const safeLevel = SvgSanitizerService.sanitizeUserContent(level || 'N/A');
    
    return SvgSanitizerService.sanitize(`<svg xmlns="http://www.w3.org/2000/svg" width="495" height="245" viewBox="0 0 495 245">
    <style>
      .text { font-family: ${theme.fonts.family}; font-size: ${theme.fonts.size.normal}; fill: ${theme.colors.text.primary}; }
      .header { font-family: ${theme.fonts.family}; font-size: ${theme.fonts.size.title}; font-weight: bold; fill: ${theme.colors.text.title}; }
      .small { font-family: ${theme.fonts.family}; font-size: ${theme.fonts.size.small}; fill: ${theme.colors.text.secondary}; }
      .label { font-family: ${theme.fonts.family}; font-size: ${theme.fonts.size.normal}; fill: ${theme.colors.text.secondary}; }
      .value { font-family: ${theme.fonts.family}; font-size: ${theme.fonts.size.normal}; font-weight: bold; }
      .footer { font-family: ${theme.fonts.family}; font-size: 10px; fill: ${theme.colors.text.secondary}; }
    </style>
    <rect width="495" height="245" fill="${theme.colors.background}" rx="${theme.card.borderRadius}" ry="${theme.card.borderRadius}" stroke="${theme.colors.border}" stroke-width="1"/>
    
    <!-- 标题和用户名 -->
    <text x="25" y="35" class="header">CSDN 统计</text>
    <text x="465" y="35" text-anchor="end" class="small">用户: ${safeUsername}</text>
    
    <!-- 分隔线 -->
    <rect x="25" y="50" width="445" height="1" fill="${theme.colors.border}"/>
    
    <!-- 统计数据第一行 -->
    <g transform="translate(40, 85)">
      <!-- 文章数量 -->
      <text x="0" y="0" class="label">文章:</text>
      <text x="55" y="0" class="value" fill="${theme.colors.stats.total}">${formatNumber(articleCount)}</text>
      
      <!-- 粉丝数 -->
      <text x="150" y="0" class="label">粉丝:</text>
      <text x="205" y="0" class="value" fill="${theme.colors.stats.medium}">${formatNumber(followers)}</text>
      
      <!-- 排名 -->
      <text x="300" y="0" class="label">排名:</text>
      <text x="355" y="0" class="value" fill="${theme.colors.stats.hard}">${safeRank}</text>
    </g>
    
    <!-- 统计数据第二行 -->
    <g transform="translate(40, 120)">
      <!-- 访问量 -->
      <text x="0" y="0" class="label">访问量:</text>
      <text x="55" y="0" class="value" fill="${theme.colors.accent.primary}">${formatNumber(views)}</text>
      
      <!-- 点赞数 -->
      <text x="150" y="0" class="label">点赞:</text>
      <text x="205" y="0" class="value" fill="${theme.colors.stats.easy}">${formatNumber(likes)}</text>
      
      <!-- 评论数 -->
      <text x="300" y="0" class="label">评论:</text>
      <text x="355" y="0" class="value" fill="${theme.colors.stats.medium}">${formatNumber(comments)}</text>
    </g>
    
    <!-- 统计数据第三行 -->
    <g transform="translate(40, 155)">
      <!-- 码龄 -->
      <text x="0" y="0" class="label">码龄:</text>
      <text x="55" y="0" class="value" fill="${theme.colors.stats.easy}">${safeCodeAge}</text>
      
      <!-- 博客等级 -->
      <text x="150" y="0" class="label">等级:</text>
      <text x="205" y="0" class="value" fill="${theme.colors.stats.total}">${safeLevel}</text>
      
      <!-- 积分 -->
      <text x="300" y="0" class="label">总积分:</text>
      <text x="355" y="0" class="value" fill="${theme.colors.stats.count}">${formatNumber(points)}</text>
    </g>
    
    <!-- 统计数据第四行 -->
    <g transform="translate(40, 190)">
      <!-- 当月积分 -->
      <text x="0" y="0" class="label">当月分:</text>
      <text x="55" y="0" class="value" fill="${theme.colors.accent.secondary}">${formatNumber(monthPoints)}</text>
    </g>
    
    <!-- 分隔线 -->
    <rect x="25" y="210" width="445" height="1" fill="${theme.colors.border}"/>
    
    <!-- 底部信息 -->
    <text x="25" y="230" class="footer">Generated by GitHub Profile Statistics Card</text>
    <text x="465" y="230" text-anchor="end" class="footer">更新于: ${currentDate}</text>
  </svg>`);
}

/**
 * 生成掘金统计卡片
 * @param data 掘金用户数据
 * @param theme 主题配置
 * @returns SVG字符串
 */
const generateJuejinCard = (data: JuejinUserData, theme: ThemeOptions = activeTheme): string => {
    if (!data) {
        return generateErrorCard('无法获取掘金数据', theme);
    }

    const {
        username,
        desc,
        followers,
        articleCount,
        likes,
        views,
    } = data;

    // 数据格式化
    const formatNumber = (num: number): string => {
        if (num >= 1000000) {
            return (num / 1000000).toFixed(1) + 'M';
        } else if (num >= 1000) {
            return (num / 1000).toFixed(1) + 'K';
        }
        return num.toString();
    };

    // 当前日期
    const currentDate = new Date().toLocaleDateString();

    // 安全处理用户数据
    const safeUsername = SvgSanitizerService.sanitizeUserContent(username || '');
    const safeDesc = SvgSanitizerService.sanitizeUserContent(desc || '');
    
    return SvgSanitizerService.sanitize(`<svg xmlns="http://www.w3.org/2000/svg" width="495" height="245" viewBox="0 0 495 245">
    <style>
      .text { font-family: ${theme.fonts.family}; font-size: ${theme.fonts.size.normal}; fill: ${theme.colors.text.primary}; }
      .header { font-family: ${theme.fonts.family}; font-size: ${theme.fonts.size.title}; font-weight: bold; fill: ${theme.colors.text.title}; }
      .small { font-family: ${theme.fonts.family}; font-size: ${theme.fonts.size.small}; fill: ${theme.colors.text.secondary}; }
      .label { font-family: ${theme.fonts.family}; font-size: ${theme.fonts.size.normal}; fill: ${theme.colors.text.secondary}; }
      .value { font-family: ${theme.fonts.family}; font-size: ${theme.fonts.size.normal}; font-weight: bold; fill: ${theme.colors.text.secondary}; }
      .footer { font-family: ${theme.fonts.family}; font-size: 10px; fill: ${theme.colors.text.secondary}; }
      .power { font-family: ${theme.fonts.family}; font-size: 12px; font-weight: bold; fill: #1E80FF; }
    </style>
    
    <rect width="495" height="245" fill="${theme.colors.background}" rx="${theme.card.borderRadius}" ry="${theme.card.borderRadius}" stroke="${theme.colors.border}" stroke-width="1"/>
    
    <!-- 标题和用户名 -->
    <text x="25" y="35" class="header">掘金统计</text>
    <text x="465" y="35" text-anchor="end" class="small">用户: ${safeUsername}</text>
    
    <!-- 分隔线 -->
    <rect x="25" y="80" width="445" height="1" fill="${theme.colors.border}"/>
    
    <!-- 统计数据 - 左侧 -->
    <text x="25" y="110" class="label">文章数:</text>
    <text x="150" y="110" class="value">${formatNumber(articleCount)}</text>
    
    <text x="25" y="140" class="label">总浏览量:</text>
    <text x="150" y="140" class="value">${formatNumber(views)}</text>
    
    <text x="25" y="170" class="label">总点赞数:</text>
    <text x="150" y="170" class="value">${formatNumber(likes)}</text>
    
    <!-- 统计数据 - 右侧 -->
    <text x="250" y="110" class="label">关注者:</text>
    <text x="375" y="110" class="value">${formatNumber(followers)}</text>
    
    <text x="250" y="140" class="label">个人简介:</text>
    <text x="375" y="140" class="value">${safeDesc}</text>
    
    <!-- 分隔线 -->
    <rect x="25" y="200" width="445" height="1" fill="${theme.colors.border}"/>
    
    <!-- 底部信息 -->
    <text x="25" y="225" class="footer">Generated by GitHub Profile Statistics Card</text>
    <text x="465" y="225" text-anchor="end" class="footer">更新时间: ${currentDate}</text>
  </svg>`);
}

/**
 * 生成哔哩哔哩统计卡片
 * @param data 哔哩哔哩用户数据
 * @param theme 主题配置
 * @returns SVG字符串
 */
const generateBilibiliCard = (data: any, theme: ThemeOptions = activeTheme): string => {
    if (!data) {
        return generateErrorCard('无法获取哔哩哔哩数据', theme);
    }

    const {
        uid,
        username,
        level,
        sign,
        followers,
        following,
        likes,
        views,
        isValid
    } = data;

    // 数据格式化
    const formatNumber = (num: number): string => {
        if (num >= 1000000) {
            return (num / 1000000).toFixed(1) + 'M';
        } else if (num >= 1000) {
            return (num / 1000).toFixed(1) + 'K';
        }
        return num.toString();
    };

    // 当前日期
    const currentDate = new Date().toLocaleDateString();

    // 安全处理用户数据
    const safeUsername = SvgSanitizerService.sanitizeUserContent(username || '');
    const safeSign = SvgSanitizerService.sanitizeUserContent(sign || '这个人很懒，什么都没写');
    
    return SvgSanitizerService.sanitize(`<svg xmlns="http://www.w3.org/2000/svg" width="495" height="245" viewBox="0 0 495 245">
    <style>
      .text { font-family: ${theme.fonts.family}; font-size: ${theme.fonts.size.normal}; fill: ${theme.colors.text.primary}; }
      .header { font-family: ${theme.fonts.family}; font-size: ${theme.fonts.size.title}; font-weight: bold; fill: ${theme.colors.text.title}; }
      .small { font-family: ${theme.fonts.family}; font-size: ${theme.fonts.size.small}; fill: ${theme.colors.text.secondary}; }
      .label { font-family: ${theme.fonts.family}; font-size: ${theme.fonts.size.normal}; fill: ${theme.colors.text.secondary}; }
      .value { font-family: ${theme.fonts.family}; font-size: ${theme.fonts.size.normal}; font-weight: bold; }
      .footer { font-family: ${theme.fonts.family}; font-size: 10px; fill: ${theme.colors.text.secondary}; }
      .invalid { font-family: ${theme.fonts.family}; font-size: 10px; fill: #dc3545; }
    </style>
    
    <rect width="495" height="245" fill="${theme.colors.background}" rx="${theme.card.borderRadius}" ry="${theme.card.borderRadius}" stroke="${theme.colors.border}" stroke-width="1"/>
    
    <!-- 标题区域 -->
    <text x="25" y="35" class="header">哔哩哔哩统计</text>
    <text x="465" y="35" text-anchor="end" class="small">用户: ${safeUsername}</text>
    
    <!-- 等级和签名 -->
    <g transform="translate(25, 65)">
      <text class="small">Lv.${level}</text>
      <text x="111" class="small" fill="${theme.colors.text.secondary}">${safeSign}</text>
    </g>
    
    <!-- 分隔线 -->
    <rect x="25" y="80" width="445" height="1" fill="${theme.colors.border}"/>
    
    <!-- 统计数据 - 使用网格布局 -->
    <g transform="translate(0, 120)">
      <!-- 第一行 -->
      <g transform="translate(25, 0)">
        <text x="0" class="label">粉丝数:</text>
        <text x="100" class="value" fill="${theme.colors.stats.total}">${formatNumber(followers)}</text>
      </g>
      
      <g transform="translate(260, 0)">
        <text x="0" class="label">获赞数:</text>
        <text x="100" class="value" fill="${theme.colors.stats.easy}">${formatNumber(likes)}</text>
      </g>
      
      <!-- 第二行 -->
      <g transform="translate(25, 40)">
        <text x="0" class="label">关注数:</text>
        <text x="100" class="value" fill="${theme.colors.stats.medium}">${formatNumber(following)}</text>
      </g>
      
      <g transform="translate(260, 40)">
        <text x="0" class="label">播放量:</text>
        <text x="100" class="value" fill="${theme.colors.accent.primary}">${formatNumber(views)}</text>
      </g>
    </g>
    
    <!-- 分隔线 -->
    <rect x="25" y="200" width="445" height="1" fill="${theme.colors.border}"/>
    
    <!-- 底部信息 -->
    <g transform="translate(0, 225)">
      <text x="25" class="footer">Generated by GitHub Profile Statistics Card</text>
      <text x="465" text-anchor="end" class="footer">更新时间: ${currentDate}</text>
    </g>
  </svg>`);
}

/**
 * 获取主题配置
 * @param themeName 主题名称或主题配置对象
 * @returns 主题配置对象
 */
export const getThemeConfig = (themeName?: string | ThemeOptions): ThemeOptions => {
    // 如果传入的是ThemeOptions对象，直接返回
    if (themeName && typeof themeName !== 'string') {
        return themeName;
    }
    
    // 如果传入的是主题名称，从themes对象中查找
    if (themeName && typeof themeName === 'string' && themes[themeName as keyof typeof themes]) {
        return themes[themeName as keyof typeof themes];
    }
    
    // 默认返回activeTheme
    return activeTheme;
};

/**
 * 通用卡片生成器 - 根据类型生成对应的卡片
 * @param type 卡片类型
 * @param data 卡片数据
 * @param theme 主题配置或主题名称
 * @returns SVG字符串
 */
export const generateCard = (
    type: CardType,
    data: any,
    theme?: string | ThemeOptions
): string => {
    try {
        // 解析主题配置
        const themeConfig = getThemeConfig(theme);
        
        // 根据卡片类型调用对应的生成函数
        switch (type) {
            case CardType.LEETCODE:
                return generateLeetCodeCard(data as ILeetCodeUser, themeConfig);

            case CardType.GITHUB:
                if (typeof data === 'number') {
                    return generateGitHubCounterCard(data, null, '', themeConfig);
                } else if (data && typeof data === 'object') {
                    const {count, avatarUrl, username} = data;
                    return generateGitHubCounterCard(count, avatarUrl, username, themeConfig);
                }
                return generateErrorCard('GitHub数据格式错误', themeConfig);

            case CardType.CSDN:
                return generateCSDNCard(data, themeConfig);

            case CardType.JUEJIN:
                return generateJuejinCard(data as JuejinUserData, themeConfig);

            case CardType.BILIBILI:
                return generateBilibiliCard(data, themeConfig);

            case CardType.ERROR:
                return generateErrorCard(data as string, themeConfig);

            default:
                const safeType = SvgSanitizerService.sanitizeUserContent(String(type));
                return generateErrorCard(`未知卡片类型: ${safeType}`, themeConfig);
        }
    } catch (error) {
        // 捕获任何生成过程中的错误
        const errorMessage = error instanceof Error ? error.message : '生成卡片失败';
        return generateErrorCard(errorMessage, activeTheme);
    }
}

/**
 * 生成错误卡片
 * @param message 错误信息
 * @param theme 主题配置或主题名称
 * @returns SVG字符串
 */
export const generateErrorCard = (message: string, theme?: string | ThemeOptions): string => {
    // 解析主题配置
    const themeConfig = getThemeConfig(theme);
    // 安全处理错误消息
    const safeMessage = SvgSanitizerService.sanitizeUserContent(message);
    
    // 生成SVG内容
    let svg = `<svg xmlns="http://www.w3.org/2000/svg" width="495" height="120" viewBox="0 0 495 120">
    <rect width="495" height="120" fill="${themeConfig.colors.background}" rx="${themeConfig.card.borderRadius}" ry="${themeConfig.card.borderRadius}" stroke="${themeConfig.colors.border}" stroke-width="1"/>
    <text x="247.5" y="60" font-family="${themeConfig.fonts.family}" font-size="${themeConfig.fonts.size.normal}" text-anchor="middle" fill="#dc3545">
       ${safeMessage}
     </text>
   </svg>`;
    
    return SvgSanitizerService.sanitize(svg);
}
